import 'package:enterprise_v6_app/app/components/custom_modele/my_columnar_bar.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/constans/dict_data_info.dart';
import 'package:enterprise_v6_app/app/core/constans/weather_info.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/location_util.dart';
import 'package:enterprise_v6_app/app/core/utils/log_util.dart';
import 'package:enterprise_v6_app/app/core/utils/user_manager.dart';
import 'package:enterprise_v6_app/app/data/common/apply_page_bean.dart';
import 'package:enterprise_v6_app/app/data/common/charts_pie.dart';
import 'package:enterprise_v6_app/app/data/common/role_menu_tree_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/apply_bean.dart';
import 'package:enterprise_v6_app/app/data/entities/auth/weather_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/double_control/risk_control_assessment_entity.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart' as geo;
import 'package:syncfusion_flutter_charts/charts.dart';

class ApplyController extends GetxController {
  /// 所有的应用列表
  List<ApplyBean> allApplyList = [];

  /// 首页显示应用列表
  List<ApplyBean> applyList = [];

  /// 应用路由名称与子类菜单名称对应关系
  Map<String, List<RoleMenuTreeEntity>> roleMenuMap = {};

  /// 我的当前任务
  List<ApplyPageBean> currentTask = [];

  /// 企业双重预防上周完成情况
  List<ApplyPageBean> preventionLastWeek = [];

  /// 企业双重预防上周完成情况-评估等级
  /// 0:差 1：中 2：良 3：优
  int? scoreLevel;

  ///饼图点击提示
  late TooltipBehavior initialTooltip;
  late TooltipBehavior surplusTooltip;

  /// 双重预防机制(当年) - 初始风险
  List<ApplyPageBean> initialPreventionThatYearRisk = [];

  /// 双重预防机制(当年) - 剩余风险数
  List<ApplyPageBean> surplusPreventionThatYearRisk = [];

  ///双重预防机制(当年) - 隐患数据
  List<MyMultipleXAxisStruct> hiddenDangerAxisList = [];

  ///隐患数据 设置为X轴中最大的值
  double hiddenDangerYAxis = 0;

  /// 当前天气信息
  WeatherLives? weather;

  /// 当前位置信息
  geo.Position? currPosition;

  /// 地理位置信息
  Placemark? currentPlace;

  @override
  void onInit() {
    super.onInit();
    initialTooltip = TooltipBehavior(enable: true, format: 'point.x : point.y');
    surplusTooltip = TooltipBehavior(enable: true, format: 'point.x : point.y');
    // 没有登录时不执行操作
    if (!UserManager.isLoggedIn) {
      return;
    }
    // 获取特殊作业字典数据
    _getDictByWorkType();
    // 获取应用信息
    // _getApplicationData();
    /// 获取当前角色的菜单(从后台根据权限获取应用信息)
    /// 登录 [http://192.168.50.131:30002/#/seal/enterprise/configuration]
    /// 应用中心-企业应用-企业安全系统-稍右侧处APP端 进行配置后
    /// 客户管理-企业客户-企业配置-选择对应企业-稍右侧处授权中心-APP-勾选权限
    _getMenuTreeByRole();
    // 获取我的当前任务完成率
    _getCurrentTaskData();
    // 获取企业双重预防上周完成情况
    _getPreventionLastWeekData();
    // 获取双重预防机制(当年)-风险
    _getPreventionThatYearData();
    // 获取天气信息
    _weatherInformation();
    // 获取位置信息
    _getLocation();
  }

  /// 获取位置信息
  _getLocation() async {
    LocationUtil.listenLocation();
    currPosition = await LocationUtil.getCurrentLocation();
    if (currPosition != null) {
      final List<Placemark> placemarks = await placemarkFromCoordinates(
        currPosition!.latitude,
        currPosition!.longitude,
      );
      if (placemarks.isNotEmpty) {
        currentPlace = placemarks[0];
        AppLogger.printLog('-----位置信息:${placemarks[0].toJson()}}');
        update(['searchView']);
      } else {
        AppToast.showWarning('无法获取地理位置信息!');
      }
    }
  }

  /// 获取天气信息
  _weatherInformation() async {
    if (UserManager.isLoggedIn) {
      await WeatherInfo.getWeather();
      weather = WeatherInfo.weatherLives;
      update(['applyList']);
    }
  }

  /// 获取特殊作业字典数据
  _getDictByWorkType() async {
    if (UserManager.isLoggedIn) {
      DictDataInfo.getTreeDictionaryDataByWorkType();
    }
  }

  // 获取我的当前任务完成率
  _getCurrentTaskData() {
    currentTask.add(ApplyPageBean(name: '待排查', value: 0, bgColor: const Color(0xffFD6B6B)));
    currentTask.add(ApplyPageBean(name: '待整改', value: 0, bgColor: const Color(0xff469CF1)));
    currentTask.add(ApplyPageBean(name: '待验收', value: 0, bgColor: const Color(0xff00CE78)));
    currentTask.add(ApplyPageBean(name: '巡检计划', value: 0, bgColor: const Color(0xff5C6DFF)));
    currentTask.add(ApplyPageBean(name: '特殊作业', value: 0, bgColor: const Color(0xffFC9900)));
    currentTask.add(ApplyPageBean(name: '培训课程', value: 0, bgColor: const Color(0xff0256FF)));
  }

  // 获取企业双重预防上周完成情况
  _getPreventionLastWeekData() async {
    // 获取机制运行效果及评估

    final res = await HttpUtil().generateGetRequest<RiskControlAssessmentEntity>(Interface.getThreeRate).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        final data = result.data!;
        preventionLastWeek.add(ApplyPageBean(name: '风险辨识率', value: data.analysisRate, bgColor: const Color(0xff5C6DFF)));
        preventionLastWeek.add(ApplyPageBean(name: '隐患排查率', value: data.investigationRate, bgColor: const Color(0xffFD6B6B)));
        preventionLastWeek.add(ApplyPageBean(name: '隐患整改率', value: data.rectificationRate, bgColor: const Color(0xff14D2B8)));
        scoreLevel = result.data!.scoreLevel;
      }
      update(['preventionLastWeek']);
    });
  }

  // 获取企业双重预防上周完成情况-风险
  _getPreventionThatYearData() {
    // 初始风险
    // initialPreventionThatYearRisk.add(ApplyPageBean('重大风险', 0, 0, 0, const Color(0xffFD6B6B)));
    // initialPreventionThatYearRisk.add(ApplyPageBean('较大风险', 0, 0, 0, const Color(0xffFC9900)));
    // initialPreventionThatYearRisk.add(ApplyPageBean('一般风险', 0, 0, 0, const Color(0xffFFCE24)));
    // initialPreventionThatYearRisk.add(ApplyPageBean('低风险', 0, 0, 0, const Color(0xff649FFF)));
    // 剩余风险
    // surplusPreventionThatYearRisk.add(ApplyPageBean('重大风险', 0, 0, 0, const Color(0xffFD6B6B)));
    // surplusPreventionThatYearRisk.add(ApplyPageBean('较大风险', 0, 0, 0, const Color(0xffFC9900)));
    // surplusPreventionThatYearRisk.add(ApplyPageBean('一般风险', 0, 0, 0, const Color(0xffFFCE24)));
    // surplusPreventionThatYearRisk.add(ApplyPageBean('低风险', 0, 0, 0, const Color(0xff649FFF)));
    // 隐患数据
    for (int index = 0; index < 12; index++) {
      hiddenDangerAxisList.add(MyMultipleXAxisStruct(names: '${index + 1}月', color: [const Color(0xffFD6B6B), const Color(0xffFFCE24)], nums: [0, 0]));
    }
    hiddenDangerYAxis = 0;
    update();
  }

  _getApplicationData() {
    applyList.add(ApplyBean(
      '安全基础',
      const Color(0xffECF3FF),
      AppImages.icon_basic_information,
      routes: AppRoutes.basicInformation,
    ));
    applyList.add(ApplyBean(
      '双重预防',
      const Color(0xffFFF1F1),
      AppImages.icon_dual_prevention,
      routes: AppRoutes.doublePrevention,
    ));
    applyList.add(ApplyBean(
      '特殊作业',
      const Color(0xffEBFFFC),
      AppImages.icon_special_assignments,
      routes: AppRoutes.specialOperation,
    ));
    applyList.add(ApplyBean(
      '教育培训',
      const Color(0xffF0EDFF),
      AppImages.icon_education_training,
      routes: AppRoutes.educationTraining,
    ));
    applyList.add(ApplyBean(
      '智能巡检',
      const Color(0xffFFF8E8),
      AppImages.icon_intelligent_inspection,
      routes: AppRoutes.intelligentInspection,
    ));
    applyList.add(ApplyBean(
      '重大危险源',
      const Color(0xffECF3FF),
      AppImages.icon_major_hazard,
      routes: AppRoutes.majorHazardPage,
    ));
    applyList.add(ApplyBean(
      '智慧仓库',
      const Color(0xffFFF1F1),
      AppImages.icon_smart_warehouse,
      routes: AppRoutes.smartWarehouse,
    ));
    applyList.add(ApplyBean(
      '封闭化',
      const Color(0xffFFF1F1),
      AppImages.icon_isolated,
      routes: AppRoutes.closure,
    ));
    applyList.add(ApplyBean(
      '敏捷应急',
      const Color(0xffFFF1F1),
      AppImages.icon_emergency,
      routes: AppRoutes.emergency,
    ));
    applyList.add(ApplyBean(
      '清单制',
      const Color(0xffFFF1F1),
      AppImages.icon_inventory_system,
      routes: AppRoutes.inventorySystem,
    ));
    applyList.add(ApplyBean(
      '标准化',
      const Color(0xffFFF1F1),
      AppImages.icon_standardization,
      routes: AppRoutes.standardization,
    ));
    applyList.add(ApplyBean(
      '更多',
      const Color(0xffFFF1F1),
      AppImages.icon_more,
      routes: AppRoutes.demoTest,
    ));
  }

  /// 获取当前角色的菜单
  _getMenuTreeByRole() async {
    // 获取当前角色的菜单
    final res = await HttpUtil()
        .generateGetRequest<List<RoleMenuTreeEntity>>(
          Interface.getMenuTreeByRole,
          queryParameters: {'webOrApp': 2},
          enableCache: true,
        )
        .execute();
    List<RoleMenuTreeEntity> data = [];
    res.onSuccess((result) {
      data = result.data ?? [];
    });
    // 数据不为空
    if (data.isNotEmpty) {
      // 添加所有模块
      for (var item in data) {
        roleMenuMap[item.path!.trim()] = item.children!;
        // 跳过没有图标的模块
        if(item.meta!.icon!.isEmpty){
          continue;
        }
        allApplyList.add(ApplyBean(
          item.meta!.title!,
          const Color(0xffFFF1F1),
          '${AppImages.image}${item.meta!.icon!}',
          routes: item.path!.trim(),
        ));
      }
      // 只显示9项
      if (allApplyList.length > 9) {
        applyList = allApplyList.sublist(0, 9); // 截取前9条数据
      } else {
        applyList.addAll(allApplyList);
      }
      if (applyList.length == 9) {
        applyList.add(ApplyBean(
          '更多',
          const Color(0xffFFF1F1),
          AppImages.icon_more,
          routes: AppRoutes.moreApply,
        ));
      }
      update(['applyList']);
    }
  }

  //跳转到对应模块页面
  void toModulePage(ApplyBean bean) {
    if (bean.routes.trim().isNotEmpty) {
      Get.toNamed(bean.routes);
    } else {
      AppToast.show('模块暂未解锁~');
    }
  }

  // 扫码
  void scan() {
    // Get.to((){
    //   return CustomQrScanPage(onScanResult: (value) {
    //     AppToast.show('扫描结果：$value');
    //   },);
    // });
  }

  /// 当前报警统计
  var alarmData = <ChartData>[
    ChartData('a', 1, Colors.yellow),
    ChartData('b', 2, Colors.red),
    ChartData('c', 3, Colors.blue),
  ];

  int get initRiskCount {
    return alarmData.fold(0, (previousValue, element) => previousValue + element.y.toInt());
  }
}
